package com.zhu.rtda;

/**
 * 局部变量表
 * 本质是一个 Slot 数组，按索引访问
 */
public class LocalVars {
    private Slot[] slots;

    /**
     * 创建指定大小的局部变量表
     * @param maxLocals 局部变量表的最大槽位数
     */
    public LocalVars(int maxLocals) {
        if (maxLocals <= 0) {
            throw new IllegalArgumentException("maxLocals must > 0!");
        }
        this.slots = new Slot[maxLocals];
        // 初始化所有 Slot
        for (int i = 0; i < maxLocals; i++) {
            slots[i] = new Slot();
        }
    }

    // --- 存取 int 类型 ---
    public void setInt(int index, int val) {
        slots[index].setNum(val);
    }

    public int getInt(int index) {
        return slots[index].getNum();
    }

    // --- 存取 float 类型（转为 int 存储）---
    public void setFloat(int index, float val) {
        int bits = Float.floatToIntBits(val);
        slots[index].setNum(bits);
    }

    public float getFloat(int index) {
        int bits = slots[index].getNum();
        return Float.intBitsToFloat(bits);
    }

    // --- 存取 long 类型（占用两个 Slot）---
    public void setLong(int index, long val) {
        // 高32位
        slots[index].setNum((int) (val >> 32));
        // 低32位
        slots[index + 1].setNum((int) val);
    }

    public long getLong(int index) {
        long high = ((long) slots[index].getNum()) << 32;
        long low = (long) slots[index + 1].getNum();
        return high | low;
    }

    // --- 存取 double 类型（转为 long 存储）---
    public void setDouble(int index, double val) {
        long bits = Double.doubleToLongBits(val);
        setLong(index, bits);
    }

    public double getDouble(int index) {
        long bits = getLong(index);
        return Double.longBitsToDouble(bits);
    }

    // --- 存取引用类型 ---
    public void setRef(int index, InstanceOop ref) {
        slots[index].setRef(ref);
    }

    public Object getRef(int index) {
        return slots[index].getRef();
    }

    // --- 获取底层数组（用于调试）---
    public Slot[] getSlots() {
        return slots;
    }
}
